<template>
  <div class="app-container">
    <el-select v-model="linkIds" multiple filterable placeholder="请选择" style="width:100%;">
      <el-option v-for="item in list" :key="item.id" :label="item.name" :value="item.id">
      </el-option>
    </el-select>

    <div style="display: flex; justify-content: flex-end; margin-top: 40px;">
        <el-button @click.stop="close">取 消</el-button>
        <el-button type="primary" @click.stop="submitAction">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { tenant_query_art,tenant_update_art } from "@/api/tenant"

export default {
  name: 'Index',
  components: {

  },
  props: {
    uid: {
      type: Number,
    },
  },
  data() {
    return {
      list: [],
      linkIds: [],
      oldLinkIds:[],//原始选中项
    }
  },
  watch: {
    uid: {
      immediate: true,
      handler(val) {
        this.getList();
      }
    },
  },
  mounted() {
    // this.getList();
  },
  methods: {
    getList() {
      this.linkIds = [];
      this.list = [];
      tenant_query_art(this.uid).then(res => {
        this.list = res.data;

        for (let j = 0; j < this.list.length; j++) {
          const item = this.list[j];
          if(item.status == 0){
            this.linkIds.push(item.id);
            this.oldLinkIds.push(item.id);
          }
        }
      })
    },
    //提交
    submitAction(){
      console.log(this.linkIds);

      let diffArr = [];
      for(let i=0;i<this.oldLinkIds.length;i++){
        if(this.linkIds.indexOf(this.oldLinkIds[i]) == -1){
          diffArr.push(this.oldLinkIds[i]);
        }
      }
      let submitArr = [];
      for (let index = 0; index < diffArr.length; index++) {
        const element = diffArr[index];
        for (let j = 0; j < this.list.length; j++) {
          const item = this.list[j];
          if(item.id == element){
            item.tenantId = this.uid;
            item.status = 1;
            submitArr.push(item);
            break;
          }
        }
      }

      for (let index = 0; index < this.linkIds.length; index++) {
        const element = this.linkIds[index];
        for (let j = 0; j < this.list.length; j++) {
          const item = this.list[j];
          if(item.id == element){
            item.tenantId = this.uid;
            item.status = 0;
            submitArr.push(item);
            break;
          }
        }
      }

      tenant_update_art(submitArr).then(res => {
        this.$modal.msgSuccess("添加成功");

        this.list = res.data;
        this.$emit('close');
      })
    },
    close(){
      this.$emit('close');
    },
    getDiff(arr1, arr2) {
      return arr1.concat(arr2).filter((item, index, arr) => 
        arr.indexOf(item) === arr.lastIndexOf(item)
      )
    },
    getSame(arr1, arr2) {
      return [...new Set(arr1)].filter(item => 
        arr2.includes(item)
      )
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
